package com.record.utils;


import org.apache.commons.math3.distribution.FDistribution;
import java.util.*;

public class AnovaCalculator {

    public static AnovaResult oneWayAnova(List<double[]> groups) {
        int k = groups.size();
        if (k < 2) throw new IllegalArgumentException("至少需要两组数据");

        int totalN = groups.stream().mapToInt(g -> g.length).sum();
        double grandMean = groups.stream()
                .flatMapToDouble(Arrays::stream)
                .average().orElse(0.0);

        // 计算组内与组间平方和
        double ssBetween = 0.0;
        double ssWithin = 0.0;

        for (double[] g : groups) {
            double mean = Arrays.stream(g).average().orElse(0.0);
            ssBetween += g.length * Math.pow(mean - grandMean, 2);
            for (double x : g) {
                ssWithin += Math.pow(x - mean, 2);
            }
        }

        int dfBetween = k - 1;
        int dfWithin = totalN - k;
        double msBetween = ssBetween / dfBetween;
        double msWithin = ssWithin / dfWithin;

        double F = msBetween / msWithin;

        // 计算 p 值
        FDistribution fDist = new FDistribution(dfBetween, dfWithin);
        double pValue = 1 - fDist.cumulativeProbability(F);

        return new AnovaResult(F, pValue);
    }
}